#include <gflags/gflags.h>
#include <yaml-cpp/yaml.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <pthread.h>
#include <thread>
#include <zeroplusmq.h>
#include <sstream>
#include "entry.pb.h"

using namespace zeroplus::mq;

DEFINE_string(confPath, "", "yaml path");
DEFINE_int32(id, 0, "id");
DEFINE_int32(index, 0, "index");

static float pubFrequency = 1000;

int main(int argc, char **argv)
{
    gflags::ParseCommandLineFlags(&argc, &argv, true);
    try
    {
        // 加载 YAML 文件
        YAML::Node config = YAML::LoadFile(FLAGS_confPath);
        YAML::Node topics = config["admin"]["topics"];
        std::vector<std::vector<std::string>> topics2D;
        for (const auto &row : topics)
        {
            std::vector<std::string> rowVector;
            for (const auto &topic : row)
            {
                rowVector.push_back(topic.as<std::string>());
            }
            topics2D.push_back(rowVector);
        }
        // 启动
        Uri namesrvUri(config["common"]["scheme"].as<std::string>(),
                       config["common"]["ip"].as<std::string>(),
                       config["nameserver"]["port"].as<std::string>());
        ProducerController producer(namesrvUri.GetUri());
        MessageLoop loop;
        Timer timer = Timer(&loop,
                            pubFrequency,
                            Timer::kInfinite);

        auto handler = [&]()
        {
            pb::Entry entry;
            auto topicName = topics2D[FLAGS_id][FLAGS_index];
            std::stringstream ss;
            ss << "Hello, " << topicName << ": " << Utils::RandomString(5);
            entry.set_value(ss.str());
            Message msg(topicName, "Entry", entry, 0);
            producer.Publish(msg);
        };

        producer.Start();
        timer.start(handler);
        loop.run();
        return 0;
    }
    catch (const YAML::Exception &e)
    {
        std::cerr << "YAML Error: " << e.what() << std::endl;
        return 1;
    }
}
